<?php


namespace app\impl;


use app\common\lib\HisData;
use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\utils\Str;
use app\interfaces\Task;
use think\Log;

class SyncPatientInfo implements Task
{

    public function run(array $data,string $taskId): ?bool
    {

        $startDate = $data["startDate"] ?? date("Y-m-d", strtotime("-1 day"));
        $endDate = $data["endDate"] ?? date("Y-m-d", strtotime("-1 day"));

        $startDate = $endDate = "2021-08-01";

        try {
            //$data = HisData::getHisData($data["type"], $startDate, $endDate);
            $data = json_decode(file_get_contents("./huanzhe.txt"), true);

            foreach ($data as $k => $v) {
                $v["timeLine"] = $v["timeLine"] ?? [];
                $v["patientId"] = $v["id"];
                $v["deleted_at"] = 0;
                $v["created_at"] = time();
                unset($v["id"]);
                $v["relationInfo"][] = [
                    'relationType' => 0,
                    'contactName' => $v["name"],
                    'contactAddress' => Str::filterEmpty([$v['presentProvince'], $v["presentcity"], $v["presentcounty"], $v["presentAddress"]]),
                    'contactTelphone' => $v['presentTelphone'] ?: "",
                    'source' => 'his源数据'
                ];
                if (!empty($v["contactName"]) && $v["contactName"] !== $v["name"]) {
                    $v["relationInfo"][] = [
                        'relationType' => $v["relationType"],
                        'contactName' => $v["contactName"],
                        'contactAddress' => Str::filterEmpty([$v['contactAddress']]),
                        'contactTelphone' => $v['contactTelphone'] ?: "",
                        'source' => 'his源数据'
                    ];
                }
                $result = ZhyxMongo::getInstance()->setCollection("patient_info")->updateOne(["patientId" => $v["patientId"]], ['$set' => $v], ['upsert' => true]);

            }
            //执行门诊信息数据推送
            //ZhyxBeanstalkd::getInstance()->beansTalk->useTube("syncOutpatientClinic")->put(["type" => "1"]);
            //执行患者并按数据推送
            //ZhyxBeanstalkd::getInstance()->beansTalk->useTube("syncInHospital")->put(["type" => "3"]);


        } catch (\Exception $exception) {

            \think\facade\Log::record("同步患者信息异常:" . $exception->getMessage(), "error");
        }

        return true;
    }
}